import { userLogin } from '@/api/user'
import { getName, getToken, setName, setToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  name: getName() ? JSON.parse(getName()) : {}
}

const mutations = {
  saveToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  saveName(state, username) {
    state.name = username
    setName(username)
  }
}

const actions = {
  async loginAction(context, data) {
    const res = await userLogin(data)
    console.log(res)
    context.commit('saveToken', res.data.token.token)
    context.commit('saveName', res.data.user)
  },
  logout(context) {
    context.commit('saveToken', '')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

